import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:gw_github_flutter/common/global.dart';
import 'package:gw_github_flutter/common/route_name.dart';
import 'package:gw_github_flutter/models/tbSectionModel.dart';
import 'package:gw_github_flutter/route/sliver/tableview/sliverRoute_tableView_appBar.dart';
import 'package:gw_github_flutter/tools/gwGetManager.dart';
import 'package:sticky_and_expandable_list/sticky_and_expandable_list.dart';

class SliverRouteTableViewTabbar extends StatefulWidget {
  SliverRouteTableViewTabbar({Key? key}) : super(key: key);

  @override
  State<SliverRouteTableViewTabbar> createState() =>
      _SliverRouteTableViewTabbarState();
}

class _SliverRouteTableViewTabbarState
    extends State<SliverRouteTableViewTabbar> {
  var _tabs = <String>[
    "Tab 1Tab 1",
    "Tab 2",
    "Tab 3",
  ];
  var list = Global.getTBSectionsList();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: DefaultTabController(
          length: _tabs.length, // This is the number of tabs.
          child: NestedScrollView(
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return <Widget>[
                SliverOverlapAbsorber(
                  handle:
                      NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                  sliver: SliverAppBar(
                    backgroundColor: Colors.blue,
                    leading: new IconButton(
                      icon: Icon(Icons.arrow_back),
                      onPressed: () => GwGetRouteManager.pop(),
                    ),
                    title: const Text(
                      RouteName.sliverRoute_tableView_tabbar,
                      style: TextStyle(fontSize: 14),
                    ),
                    centerTitle: true,
                    pinned: true,
                    // 设置滑动导航栏的显隐
                    floating: false,
                    snap: false,
                    primary: true,
                    expandedHeight: 230.0,
                    // 阴影大小
                    elevation: 10,
                    //是否显示阴影，直接取值innerBoxIsScrolled，展开不显示阴影，合并后会显示
                    forceElevated: innerBoxIsScrolled,

                    actions: <Widget>[
                      new IconButton(
                        icon: Icon(Icons.more_horiz),
                        onPressed: () {
                          print("更多");
                        },
                      ),
                    ],

                    flexibleSpace: new FlexibleSpaceBar(
                      background:
                          Image.asset("imgs/fengjing.png", fit: BoxFit.fill),
                    ),
                  ),
                ),
                SliverPersistentHeader(
                  // 可以吸顶的TabBar
                  pinned: true,
                  delegate: StickyTabBarDelegate(
                    child: TabBar(
                      labelColor: Colors.black,
                      unselectedLabelColor: Colors.blueGrey,
                      labelStyle: TextStyle(
                        fontSize: 16,
                      ),
                      indicatorColor: Colors.red,
                      indicatorSize: TabBarIndicatorSize.label,
                      indicatorWeight: 2,
                      indicatorPadding: EdgeInsets.symmetric(horizontal: 10),
                      tabs:
                          _tabs.map((String name) => Tab(text: name)).toList(),
                    ),
                  ),
                ),
              ];
            },
            body: TabBarView(
              children: _tabs.map((String name) {
                //SafeArea 适配刘海屏的一个widget
                return SafeArea(
                  top: false,
                  bottom: false,
                  child: Builder(builder: (BuildContext context) {
                    return EasyRefresh.builder(
                      onRefresh: () async {
                        await Future.delayed(const Duration(seconds: 2));
                        if (!mounted) {
                          return;
                        }
                      },
                      childBuilder: (context, physics) {
                        return CustomScrollView(
                          physics: physics,
                          key: PageStorageKey<String>(name),
                          slivers: <Widget>[
                            SliverOverlapInjector(
                              handle: NestedScrollView
                                  .sliverOverlapAbsorberHandleFor(context),
                            ),
                            const HeaderLocator.sliver(),
                            SliverExpandableList(
                              builder: SliverExpandableChildDelegate<dynamic,
                                      TbSectionModel>(
                                  sectionList: list,
                                  sectionBuilder: (context, containerInfo) =>
                                      AnimationSectionWidget(
                                        section:
                                            list[containerInfo.sectionIndex],
                                        containerInfo: containerInfo,
                                        onStateChanged: () {
                                          //notify ExpandableListView that expand state has changed.
                                          WidgetsBinding.instance
                                              .addPostFrameCallback((_) {
                                            if (mounted) {
                                              setState(() {});
                                            }
                                          });
                                        },
                                      ),
                                  itemBuilder: (context, sectionIndex,
                                      itemIndex, index) {
                                    String item =
                                        list[sectionIndex].items?[itemIndex];
                                    return ListTile(
                                      leading: CircleAvatar(
                                        child: Text("$index"),
                                      ),
                                      title: Text(item),
                                    );
                                  }),
                            ),
                          ],
                        );
                      },
                    );
                  }),
                );
              }).toList(),
            ),
          ),
        ),
      ),
    );
  }
}

class StickyTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar child;

  StickyTabBarDelegate({required this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    // print("shrinkOffset:$shrinkOffset overlapsContent:$overlapsContent");
    return Container(color: Colors.yellow, child: this.child);
  }

  @override
  double get maxExtent => this.child.preferredSize.height;

  @override
  double get minExtent => this.child.preferredSize.height;

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return true;
  }
}
